
//% color="#006dd3" iconWidth=50 iconHeight=40
namespace scikitlearn{

    //% block="初始化机器学习模块中[TYPE]" blockType="command"
    //% TYPE.shadow="dropdown" TYPE.options="TYPE"
    export function Sklearn_init(parameter: any, block: any) {
        let type=parameter.TYPE.code; 
        if(`${type}` === '1'){
            Generator.addImport(`from sklearn.preprocessing import LabelEncoder, OrdinalEncoder`)
        }else if(`${type}` === '2'){
            Generator.addImport(`from sklearn.tree import DecisionTreeClassifier,export_graphviz`)
        }else if(`${type}` === '3'){
            Generator.addImport(`from sklearn.svm import SVC`)
        }else if(`${type}` === '4'){
            Generator.addImport(`from sklearn.cluster import KMeans`)
        }else if(`${type}` === '5'){
            Generator.addImport(`import SKLn`)
        }else if(`${type}` === '6'){
            Generator.addImport(`from sklearn.linear_model import LinearRegression\nimport numpy as np\nimport matplotlib.pyplot as plt`)

        }
       
    }
   //% block="随机划分特征" blockType="tag"
    export function noteSeptest1() {
    }

    //% block="随机划分特征集[X]标签集[Y]样本占比[SIZE]返回划分的训练特征集[XTRAIN]测试特征集[Xtest]训练标签集[YTRAIN]测试标签集[Ytest]" blockType="command"
    //% SIZE.shadow="range" SIZE.params.min=0    SIZE.params.max=1    SIZE.defl=0.3
    //% X.shadow="normal" X.defl="X"
    //% Y.shadow="normal" Y.defl="y"
    //% XTRAIN.shadow="normal" XTRAIN.defl="X_train"
    //% Xtest.shadow="normal" Xtest.defl="X_test"
    //% YTRAIN.shadow="normal" YTRAIN.defl="y_train"
    //% Ytest.shadow="normal" Ytest.defl="y_test"
    export function train_test_split(parameter: any, block: any) {
        let x=parameter.X.code;
        let y=parameter.Y.code;
        let size=parameter.SIZE.code;
 
        let xtrain=parameter.XTRAIN.code;
        let ytrain=parameter.YTRAIN.code;
        let xtest=parameter.Xtest.code;
        let ytest=parameter.Ytest.code;
        Generator.addImport(`from sklearn.model_selection import train_test_split\n`)
        Generator.addCode(`${xtrain}, ${xtest}, ${ytrain}, ${ytest} = train_test_split(${x},${y}, test_size=${size}, random_state=1)`)

    }




    //% block="对象名[OBJECT]数据特征[X]数据标签[Y]开始训练后模型返回变量[VALUE]中" blockType="command"
    //% OBJECT.shadow="normal" OBJECT.defl="clf"
    //% X.shadow="normal" X.defl="X"
    //% Y.shadow="normal" Y.defl="y"
    //% VALUE.shadow="normal" VALUE.defl="model"
    export function Sklearn_initread2(parameter: any, block: any) {
        let obj=parameter.OBJECT.code;  
        let x=parameter.X.code;  
        let y=parameter.Y.code;  
        let value=parameter.VALUE.code; 
        Generator.addCode(`${value} = ${obj}.fit(${x},${y})`) 
    }

    //% block="根据划分的测试标签集[YTEST]和预测结果[DATA]对比计算准确率" blockType="reporter"
    //% YTEST.shadow="normal" YTEST.defl="y_test"
    //% DATA.shadow="normal" DATA.defl="y_pred"
    export function accuracy_score(parameter: any, block: any) {
        let ytest=parameter.YTEST.code;
        let data=parameter.DATA.code;
        Generator.addImport(`from sklearn import metrics\n`)
        Generator.addCode(`metrics.accuracy_score(${ytest}, ${data})`)
    }  

    //% block="对象名[OBJECT]预测数据[DATA]" blockType="reporter"
    //% OBJECT.shadow="normal" OBJECT.defl="clf"
    //% DATA.shadow="normal" DATA.defl="[[2,0]]"
 
    export function Sklearn_initpredict(parameter: any, block: any) {
        let obj=parameter.OBJECT.code;  
        let data=parameter.DATA.code;  
 
        Generator.addCode(`${obj}.predict(${data})`) 
    } 

    //% block="对象名[ZXD] 获取置信度[FD2]" blockType="reporter"
    //% ZXD.shadow="normal"   ZXD.defl="clf"
    //% FD2.shadow="normal"   FD2.defl="[fd]"
    export function proba(parameter: any, block: any){ 
        let zxd = parameter.ZXD.code
        let fd2 = parameter.FD2.code
        Generator.addCode(`${zxd}.predict_proba(${fd2}) `);
    }

    //% block="保存训练后的模型文件[OBJECT] 路径[DATA]" blockType="command"
    //% OBJECT.shadow="normal" OBJECT.defl="model"
    //% DATA.shadow="normal" DATA.defl="model.pkl"
    export function Sklearn_initsavetrain(parameter: any, block: any) {
        let obj=parameter.OBJECT.code;  
        let data=parameter.DATA.code;  
        
        Generator.addImport(`import joblib\n`)
        Generator.addCode(`joblib.dump(${obj},"${data}")`) 
    }   

    //% block="导入训练后的模型文件路径[DATA]的结果返回变量[VALVE]中" blockType="command"
    //% VALVE.shadow="normal" VALVE.defl="DT_model"
    //% DATA.shadow="normal" DATA.defl="model.pkl"
    export function Sklearn_initloadtrain(parameter: any, block: any) {
        let value=parameter.VALVE.code; 
        let data=parameter.DATA.code;  
        Generator.addImport(`import joblib\n`)
        Generator.addCode(`${value} = joblib.load("${data}")`) 
    }  

    //%block="对象名[PATHNAME]将文件[FILEPATH]转化为路径"blockType="command"
    //% FILEPATH.shadow="normal"   FILEPATH.defl="file_dir"
    //% PATHNAME.shadow="normal"   PATHNAME.defl="pos_img_files"
    export function os(parameter: any, block: any){
        let filepath = parameter.FILEPATH.code
        let pathname = parameter.PATHNAME.code
        Generator.addImport("import os");
        Generator.addCode(`${pathname} = os.listdir(${filepath})`);
        
    }


   //% block="特征编码" blockType="tag"
    export function noteSeptest2() {
    }


    //% block="创建特征编码器[OBJECT]" blockType="command"
    //% OBJECT.shadow="normal" OBJECT.defl="Labellencoder"
    export function Sklearn_initOBJ(parameter: any, block: any) {
        let obj=parameter.OBJECT.code;  
        Generator.addCode(`${obj} = LabelEncoder()`)  
    }
    //% block="对象名[OBJECT]经编码器拟合并标准化[STR]的数据结果返回变量[VALUE]中" blockType="command"
    //% OBJECT.shadow="normal" OBJECT.defl="Labellencoder"
    //% STR.shadow="normal" STR.defl="period"
    //% VALUE.shadow="normal" VALUE.defl="Labellen"
    export function Sklearn_initread(parameter: any, block: any) {
        let obj=parameter.OBJECT.code;  
        let str=parameter.STR.code;  
        let value=parameter.VALUE.code; 
        Generator.addCode(`${value} = ${obj}.fit_transform(${str}.ravel())`) 
    }

   //% block="决策树" blockType="tag"
    export function noteSeptest3() {
    }

    //% block="对象名[OBJECT]创建决策树分类器并设置最大深度[NUM]" blockType="command"
    //% OBJECT.shadow="normal" OBJECT.defl="clf"
    //% NUM.shadow="number" NUM.defl="4"
    export function Sklearn_inittree(parameter: any, block: any) {
        let obj=parameter.OBJECT.code;  
        let num=parameter.NUM.code;  
        Generator.addCode(`${obj} = DecisionTreeClassifier(criterion='entropy',max_depth=${num}, random_state=1)`)  
    }


 
    //% block="绘制决策树 模型文件[OBJECT] 特征名称[DATA]" blockType="command"
    //% OBJECT.shadow="normal" OBJECT.defl="model"
    //% DATA.shadow="normal" DATA.defl="'不开空调','开空调'"
    export function Sklearn_inittreetrain(parameter: any, block: any) {
        let obj=parameter.OBJECT.code;  
        let data=parameter.DATA.code;  
        Generator.addImport(`from six import StringIO\nfrom IPython.display import Image\nimport pydotplus`)
        Generator.addCode(`        
dot_data = StringIO()
export_graphviz(${obj}, out_file=dot_data,
    filled=True,rounded=True,special_characters=True,
    feature_names = feature_cols,class_names=[${data}])
dot_data1 = dot_data.getvalue()
dot_data1 = dot_data1.replace('\\n','')
graph = pydotplus.graph_from_dot_data(dot_data1)
Image(graph.create_png())`) 
    } 

    //% block="保存绘制决策树图片名[DATA].png" blockType="command"
    //% DATA.shadow="normal" DATA.defl="决策树_温度_二氧化碳"
    export function Sklearn_initsavepng(parameter: any, block: any) {
   
        let data=parameter.DATA.code;  
        Generator.addCode(`graph.write_png("${data}.png")`) 
    } 



   //% block="支持向量机" blockType="tag"
    export function noteSeptest4() {
    }


    //%block="对象名[SVM1]新建一个SVM分类器"blockType="command"
    //% SVM1.shadow="normal"   SVM1.defl="clf"
    export function svm_creat(parameter: any, block: any){
        let svm1 = parameter.SVM1.code
        Generator.addCode(`${svm1} = SVC(random_state = 30,probability=True)`)
        
    }

 
   //% block="K均值" blockType="tag"
    export function noteSeptest5() {
    }


    //% block="对象名[MONAME]训练数据[DATA2]为聚类模型，K值为[NM2]" blockType="command"
    //% MONAME.shadow="normal"   MONAME.defl="kmeans"
    //% DATA2.shadow="normal"   DATA2.defl="data_name"
    //% NM2.shadow="number"   NM2.defl="3"
    export function kmeans_train(parameter: any, block: any){ 
        let moname = parameter.MONAME.code
        let data2 = parameter.DATA2.code
        let nm2 = parameter.NM2.code
        Generator.addCode(`${moname} = KMeans(n_clusters=${nm2})`);
        Generator.addCode(`${moname}.fit(${data2})`);

   }

    //% block="将聚类标签映射到[LAB2]并保存为[PKL]" blockType="command"
    //% LAB2.shadow="normal"   LAB2.defl="data_name"
    //% PKL.shadow="normal"   PKL.defl="name.pkl"
    export function map(parameter: any, block: any){ 
        let lab2 = parameter.LAB2.code
        let pkl = parameter.PKL.code
        Generator.addCode(`
_,idx = np.unique(kmeans.labels_, return_index=True)
mapping_label = dict(zip(kmeans.labels_[np.sort(idx)], ${lab2}))
joblib.dump(mapping_label, "${pkl}")
        `);

   }
   //% block="线性回归" blockType="tag"
    export function noteSeptest6() {
    }
    //% block="实例化 线性回归直线，训练X轴数据集[X_DATA]Y轴数据集[Y_DATA]" blockType="command"
    //% X_DATA.shadow="normal" X_DATA.defl="X_DATA"
    //% Y_DATA.shadow="normal" Y_DATA.defl="Y_DATA"
    export function train_test_split1(parameter: any, block: any) {
        let x=parameter.X_DATA.code;
        let y=parameter.Y_DATA.code;

        Generator.addCode(`Sklearn_linear_model = LinearRegression()\nSklearn_linear_model.fit(np.array(${x}).reshape(-1, 1),np.array(${y}))`)

    }
    //% block="获取[MD]" blockType="reporter"
    //% MD.shadow="dropdown" MD.options="MD"
    export function Sklearn_initpredict12(parameter: any, block: any) {
 
        let data=parameter.MD.code;  
        if(data === "coef_"){
             Generator.addCode(`Sklearn_linear_model.coef_[0]`)
        }else{
            Generator.addCode(`Sklearn_linear_model.${data}`)

        }
       
    } 
    //% block="预测数据[DATA]" blockType="reporter"
    //% DATA.shadow="normal" DATA.defl="20"
 
    export function Sklearn_initpredict1(parameter: any, block: any) {
 
        let data=parameter.DATA.code;  
 
        Generator.addCode(`Sklearn_linear_model.predict(np.array([${data}]).reshape(-1, 1))[0]`)   
    } 
    //% block="---"
    export function noteSep6() {

    }
    //% block="标题[TEXT]字号[NUMBER]字体[FONT]" blockType="command"
    //% TEXT.shadow="string" TEXT.defl="标题"
    //% NUMBER.shadow="normal" NUMBER.defl="15"
    //% FONT.shadow="dropdown" FONT.options="FONT"
    export function matplotlib_title(parameter: any, block: any) {
 
        let te=parameter.TEXT.code;  
        let nu=parameter.NUMBER.code;  
        let font =parameter.FONT.code;  
        if(`${font}`===`HYQiHei`){
         
            Generator.addCode(`plt.figure(figsize=(8, 7),dpi=90)\nplt.subplots_adjust(left=20/100,bottom=15/100)\nplt.rcParams["font.sans-serif"] = ["${font}"]\nplt.title(${te},color='black',size="${nu}")`) 
        }else{

            Generator.addCode(`plt.rcParams["font.sans-serif"] = ["${font}"]\nplt.title(${te},color='black',size="${nu}")`) 
  
        }
    } 
    //% block="标签[XY]标题[TEXT]字号[SIZE]" blockType="command"
    //% XY.shadow="dropdown" XY.options="XY"
    //% TEXT.shadow="string" TEXT.defl="X轴"
    //% SIZE.shadow="number" SIZE.defl="10"
    export function matplotlib_label(parameter: any, block: any) {
        let xy=parameter.XY.code;
        let text=parameter.TEXT.code;
        let size=parameter.SIZE.code;
        Generator.addCode(`plt.${xy}label(${text}, fontsize=${size})`)
             
    }

    //% block="真实数据[X][Y] 符号标记[TYPE1] 颜色r[R]g[G]b[B]标题[TEXT]" blockType="command"
    //% X.shadow="normal" X.defl="X_DATA"
    //% Y.shadow="normal" Y.defl="Y_DATA"
    //% TYPE1.shadow="dropdown" TYPE1.options="TYPE1"
    //% R.shadow="number" R.defl="255"
    //% G.shadow="number" G.defl="0"
    //% B.shadow="number" B.defl="0"
    //% TEXT.shadow="string" TEXT.defl="标题"
    export function matplotlib_label_1(parameter: any, block: any) {
        let x=parameter.X.code;
        let y=parameter.Y.code;
        let TYPE1=parameter.TYPE1.code;
        let r=parameter.R.code;
        let g=parameter.G.code;
        let b=parameter.B.code;

        let text=parameter.TEXT.code;
 
        Generator.addCode(`plt.scatter( ${x}, ${y}, color=(${r}/255,${g}/255,${b}/255),marker=${TYPE1},label=${text})\n`)
             
    }  
    //% block="预测线性回归直线 [X][Y] 符号标记[TYPE2] 颜色r[R]g[G]b[B]标题[TEXT]" blockType="command"
    //% X.shadow="normal" X.defl="X_DATA"
    //% Y.shadow="normal" Y.defl="Y_DATA"
    //% TYPE2.shadow="dropdown" TYPE2.options="TYPE2"
    //% R.shadow="number" R.defl="0"
    //% G.shadow="number" G.defl="0"
    //% B.shadow="number" B.defl="255"
    //% TEXT.shadow="string" TEXT.defl="标题"
    export function matplotlib_label_2(parameter: any, block: any) {
        let x=parameter.X.code;
        let y=parameter.Y.code;
        let TYPE1=parameter.TYPE2.code;
        let r=parameter.R.code;
        let g=parameter.G.code;
        let b=parameter.B.code;

        let text=parameter.TEXT.code;
 
        Generator.addCode(`X_value = np.array(${x}).reshape(-1, 1)\ny_value = np.array(${x})\nX_fit = np.linspace(X_value.min(), y_value.max(), 100).reshape(-1, 1)\ny_fit = Sklearn_linear_model.predict(X_fit)\nplt.plot( X_fit, y_fit, color=(${r}/255,${g}/255,${b}/255),linestyle=${TYPE1},label=${text})`)
             
    }   
    //% block="显示图表" blockType="command"

    export function matplotlib_label_3(parameter: any, block: any) {
        Generator.addCode(`plt.legend(fontsize=8)\nplt.show()`)
    }

}


